import { getAllClassification } from '@/apis/Classification'
import { ClassificationType, type Classification } from '@/models/Classification/Classification'
import type { ClassificationTree } from '@/models/Classification/ClassificationTree'
import { notification } from 'ant-design-vue'
import { computed, ref } from 'vue'
import { getTreeByListSimple } from 'yiu-tree'

let apiCacheData: Array<Classification> = []

// export type UseClassificationDataInstance = ReturnType<typeof useClassificationData>
export function useClassificationData() {
  const list = ref<Array<Classification>>([])
  const loading = ref(false)

  async function initData() {
    if (apiCacheData.length > 0) {
      list.value = apiCacheData
      return
    }

    if (loading.value) return
    loading.value = true
    try {
      const res = await getAllClassification()
      if (Array.isArray(res.data)) {
        list.value = res.data
        apiCacheData = res.data
      } else {
        list.value = []
        apiCacheData = []
        notification.error({ message: `获取分类失败失败!` })
      }
    } catch (error) {
      list.value = []
      apiCacheData = []
      notification.error({ message: `获取分类失败失败!` })
    }
    loading.value = false
  }

  const tree = computed(() => {
    const result: Array<ClassificationTree> = getTreeByListSimple(list.value, {
      idGetter: (node) => `${node.type}&${node.code}`,
      pidGetter: (node) => {
        if (node.type === 'classification') return ''
        return `${ClassificationType.classification}&${node.parentCode}`
      },
    })
    return result
  })

  return { list, tree, loading, initData }
}
